﻿using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace Translator
{
	public static class Translator
	{
		/// <summary>
		/// Translates the text.
		/// </summary>
		/// <param name="input">The input.</param>
		/// <param name="languagePair">The language pair.</param>
		/// <returns></returns>
		public static string TranslateText(string input, string languagePair)
		{
			return TranslateText(input, languagePair, System.Text.Encoding.UTF7);
		}

		/// <summary>
		/// Translate Text using Google Translate
		/// </summary>
		/// <param name="input">The string you want translated</param>
		/// <param name="languagePair">2 letter Language Pair, delimited by "|". 
		/// e.g. "en|da" language pair means to translate from English to Danish</param>
		/// <param name="encoding">The encoding.</param>
		/// <returns>Translated to String</returns>
		public static string TranslateText(string input, string languagePair, Encoding encoding)
		{
			string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);

			string result = String.Empty;

			using (WebClient webClient = new WebClient())
			{
				webClient.Encoding = encoding;
				result = webClient.DownloadString(url);
			}

			Match m = Regex.Match(result, "(?<=<div id=result_box dir=\"ltr\">)(.*?)(?=</div>)");

			if (m.Success)
				result = m.Value;

			return result;
		}

		// <summary>
		/// Translate Text using Google Translate API's
		/// Google URL - http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}
		/// </summary>
		/// <param name="input">Input string</param>
		/// <param name="languagePair">2 letter Language Pair, delimited by "|".
		/// E.g. "ar|en" language pair means to translate from Arabic to English</param>
		/// <returns>Translated to String</returns>
		public static string TranslateText2(string input, string languagePair)
		{
			string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
			WebClient webClient = new WebClient();
			webClient.Encoding = System.Text.Encoding.UTF8;
			string result = webClient.DownloadString(url);
			result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
			result = result.Substring(0, result.IndexOf("</div"));
			return result;
		}
	}
}